package eproject.mm.com.projectsupervision.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import eproject.mm.com.projectsupervision.BuildConfig;
import eproject.mm.com.projectsupervision.PrjApplication;
import eproject.mm.com.projectsupervision.R;
import eproject.mm.com.projectsupervision.adapter.PassengerAdapter;
import eproject.mm.com.projectsupervision.widget.CustomDatePicker;
import eproject.mm.com.projectsupervision.widget.IconFontTextview;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ProblemActivity extends Activity {
    private static final String TAG = ProblemActivity.class.getName();

    private static final int RequestCode_ProjectSelect = 10005;
    private static final int RequestCode_PlanNodeSelect = 10006;
    private static final int RequestCode_BuildUnitSelect = 10007;

    public static final String TYPE = "application/octet-stream";

    ImageView iv_takePhoto;
    RecyclerView rv_photos;
    PassengerAdapter passengerAdapter;
    ArrayList imageUrls;
    int poss;

    //==========
    String sPrjId = "";
    TextView tv_PrjName;
    String sPlanNodeId = "";
    TextView tv_PlanNode;
    EditText et_intro;
    TextView tv_date;
    String sBuildUnitId = "";
    TextView tv_buildUnit;
    //==========
    String imageFilePath,imageFileName;

    private OkHttpClient client;

    CustomDatePicker customDatePicker;
    IconFontTextview iftv_back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_problem);

        initView();
        initEvent();

        iftv_back = (IconFontTextview)findViewById(R.id.iftv_back);
        iftv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        loadData();

        client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
    }

    private void initView(){
        //iv_takePhoto = (ImageView)findViewById(R.id.iv_takePhoto);
        rv_photos = (RecyclerView)findViewById(R.id.rv_photos);
        tv_PrjName = (TextView)findViewById(R.id.tv_prjName);
        tv_PlanNode = (TextView)findViewById(R.id.tv_PlanNode);
        et_intro = (EditText) findViewById(R.id.et_intro);

        et_intro.setHintTextColor(Color.GRAY);
        tv_date = (TextView) findViewById(R.id.tv_date);

        tv_buildUnit = (TextView)findViewById(R.id.tv_buildUnit);
        initDatePicker();
    }
    private void initEvent(){

    }

    private void loadData(){
        imageUrls = new ArrayList();
        imageUrls.add("hehe");

        passengerAdapter = new PassengerAdapter(this, imageUrls);

        rv_photos.setLayoutManager(new GridLayoutManager(this, 4) {
            @Override
            public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
                super.onMeasure(recycler, state, widthSpec, heightSpec);
            }
        });
        rv_photos.getLayoutManager().setAutoMeasureEnabled(true);
        rv_photos.setAdapter(passengerAdapter);

        passengerAdapter.setOnItemClickLitener(new PassengerAdapter.OnItemClickLitener() {
            @Override
            public void onBigClick(int position) {
                if (position==imageUrls.size()-1) {

                    String name = new SimpleDateFormat("yyyyMMddhhmmssSSS").format(new Date());

                    //File outputImage = new File(getExternalCacheDir(),name+".jpg");
                    File outputImage = new File(Environment.getExternalStorageDirectory(),name+".jpg");
                    imageFilePath = outputImage.getPath();

                    android.net.Uri imageUri;
                    if(outputImage.exists())
                    {
                        outputImage.delete();
                        try
                        {
                            outputImage.createNewFile();
                        }
                        catch (IOException e)
                        {
                            e.printStackTrace();
                        }
                    }
                    imageFileName = outputImage.getName();
                    if (Build.VERSION.SDK_INT>=24)
                    {
                        //imageUri = FileProvider.getUriForFile(ReportActivity.this,"eproject.mm.com.projectsupervision.fileProvider",outputImage);
                        imageUri = FileProvider.getUriForFile(ProblemActivity.this, BuildConfig.APPLICATION_ID+".provider",outputImage);

                    }else{
                        imageUri = Uri.fromFile(outputImage);
                        imageFilePath = imageUri.getPath();
                    }

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

                        if ((ContextCompat.checkSelfPermission(ProblemActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)||
                                (ContextCompat.checkSelfPermission(ProblemActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
                            //如果没有授权，则请求授权
                            ActivityCompat.requestPermissions(ProblemActivity.this, new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                        } else {
                            //有授权，直接开启摄像头
                            //6.0 camera

                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            if (intent.resolveActivity(getPackageManager())!=null){
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                                startActivityForResult(intent, 1);
                            }
                        }
                    }else{
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                        intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                        startActivityForResult(intent,1);
                    }
                }
            }
            @Override
            public void onSmallClick(int position) {
                imageUrls.remove(position);
                passengerAdapter.notifyItemRemoved(position);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //if(data!=null){
        if(requestCode == RequestCode_ProjectSelect && data != null){
            Bundle bundle = data.getExtras();
            String id = bundle.getString("id");
            String name = bundle.getString("name");

            sPrjId = id;
            tv_PrjName.setText(name);
        }else if(requestCode == RequestCode_PlanNodeSelect && data != null){
            Bundle bundle = data.getExtras();
            String id = bundle.getString("id");
            String name = bundle.getString("name");

            sPlanNodeId = id;
            tv_PlanNode.setText(name);
        }else if(requestCode == 1){
            if(resultCode == RESULT_OK){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        imageUrls.add(0,imageFilePath);
                        //更新第一个位置的图片
                        passengerAdapter.notifyItemInserted(0);
                    }
                });
            }
        }else if(requestCode == RequestCode_BuildUnitSelect && data != null){
            Bundle bundle = data.getExtras();
            String id = bundle.getString("id");
            String name = bundle.getString("name");

            sBuildUnitId = id;
            tv_buildUnit.setText(name);
        }
        //}

    }

    public void onSubmit(View view){
        if(sPrjId.equals("")){
            Toast.makeText(this,"请选择项目",Toast.LENGTH_SHORT).show();
            return;
        }
        if(sPlanNodeId.equals("")){
            Toast.makeText(this,"请选择计划节点",Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_intro.getText().toString().trim().equals("")){
            Toast.makeText(this,"请输入问题描述",Toast.LENGTH_SHORT).show();
            return;
        }
        if(sBuildUnitId.equals("")){
            Toast.makeText(this,"请选择施工单位",Toast.LENGTH_SHORT).show();
            return;
        }

        final LoadingDialog loadingDialog = new LoadingDialog(this);
        loadingDialog.setLoadingText("加载中...")//设置loading时显示的文字
                .show();

        MultipartBody.Builder builder = new MultipartBody.Builder();

        for(int i=0; i < imageUrls.size()-1; i++) {
            String filePath = (String)imageUrls.get(i);
            File imageFile = new File(filePath);
            RequestBody fileBody = RequestBody.create(MediaType.parse(TYPE), imageFile);
            builder.addFormDataPart("files", imageFile.getName(), fileBody);
        }
        builder.addFormDataPart("project",sPrjId);
        builder.addFormDataPart("task",sPlanNodeId);
        builder.addFormDataPart("limitdate",tv_date.getText().toString());
        builder.addFormDataPart("describes",et_intro.getText().toString());
        builder.addFormDataPart("buildunit",sBuildUnitId);
        builder.addFormDataPart("type","0");//新提交问题
        builder.addFormDataPart("parent","");
        builder.addFormDataPart("root","");

        RequestBody requestBody = builder.build();

        Request.Builder okbuilder = new Request.Builder();
        okbuilder.addHeader("authenticationToken", PrjApplication.getInstance().getAuthenticationToken());
        Request requestPostFile = okbuilder
                .url("http://"+ PrjApplication.getInstance().getServerIp() +":"+PrjApplication.getInstance().getServerPort()+"/"+PrjApplication.getInstance().getPreFixPath()+"/problemSubmit")
                .post(requestBody)
                .build();
        client.newCall(requestPostFile).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                loadingDialog.close();
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loadingDialog.close();
                        ProblemActivity.this.finish();
                    }
                });
            }
        });
    }
    public void back(View view) {
        finish();
    }

    public void onPlanNodeClick(View view){
        if(sPrjId.equals("")){
            Toast.makeText(this, "请先选择项目", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(ProblemActivity.this, PlanNodeActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("prjID",sPrjId);
        intent.putExtras(bundle);

        //poss = position;
        startActivityForResult(intent, RequestCode_PlanNodeSelect);//10002-->修改
    }

    public  void onProjectSelectClick(View view){
        Intent intent = new Intent(ProblemActivity.this, ProjectSelectActivity.class);
        //poss = position;
        startActivityForResult(intent, RequestCode_ProjectSelect);
    }

    public  void onDateSelectClick(View view){
        customDatePicker.show(tv_date.getText().toString());
    }

    private void initDatePicker() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String now = sdf.format(new Date());
        tv_date.setText(now.split(" ")[0]);

        customDatePicker = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                tv_date.setText(time.split(" ")[0]);
            }
        }, "2010-01-01 00:00", "2020-12-31 00:00"); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker.showSpecificTime(false); // 不显示时和分
        customDatePicker.setIsLoop(false); // 不允许循环滚动
    }

    public void onBuildUnitSelectClick(View v) {
        if(sPrjId.equals("")){
            Toast.makeText(this, "请先选择项目", Toast.LENGTH_SHORT).show();
            return;
        }

        Intent intent = new Intent(ProblemActivity.this, BuildUnitSelectActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("prjID",sPrjId);
        intent.putExtras(bundle);

        //poss = position;
        startActivityForResult(intent, RequestCode_BuildUnitSelect);
    }
}
